<template>
  <div class="messages-container">
    <h2 class="page-title">我的消息</h2>
    
    <!-- 消息类型选择器 -->
    <div class="message-filter">
      <el-radio-group v-model="messageType" @change="filterMessages">
        <el-radio-button label="all">全部消息</el-radio-button>
        <el-radio-button label="review_reply">评论回复</el-radio-button>
        <el-radio-button label="order_update">订单更新</el-radio-button>
        <el-radio-button label="hotel_review">酒店评价</el-radio-button>
      </el-radio-group>
      
      <el-button type="primary" @click="markAllAsRead" :disabled="!hasUnreadMessages">
        全部标为已读
      </el-button>
    </div>
    
    <!-- 消息列表 -->
    <div class="message-list">
      <el-empty v-if="filteredMessages.length === 0" description="暂无消息" />
      
      <div 
        v-for="message in filteredMessages" 
        :key="message.id" 
        class="message-card"
        :class="{ 'unread': !message.isRead }"
        @click="viewMessageDetail(message)"
      >
        <div class="message-header">
          <div class="message-title">
            <el-tag size="small" :type="getTagType(message.type)" effect="plain">
              {{ getTypeLabel(message.type) }}
            </el-tag>
            <span>{{ message.title }}</span>
          </div>
          <div class="message-time">{{ formatTime(message.createTime) }}</div>
        </div>
        
        <div class="message-content">{{ message.content }}</div>
        
        <div class="message-footer">
          <el-button 
            v-if="!message.isRead" 
            size="small" 
            type="primary" 
            text 
            @click.stop="markAsRead(message)"
            style="color: white;"
          >
            标为已读
          </el-button>
          <el-button 
            size="small" 
            type="primary" 
            text 
            @click.stop="navigateToDetail(message)"
            style="color: white;"
          >
            查看详情
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        :total="totalMessages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentMessage?.title || '消息详情'"
      width="500px"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-header">
          <el-tag size="small" :type="getTagType(currentMessage.type)" effect="plain">
            {{ getTypeLabel(currentMessage.type) }}
          </el-tag>
          <span class="detail-time">{{ formatTime(currentMessage.createTime) }}</span>
        </div>
        
        <div class="detail-content">
          {{ currentMessage.content }}
        </div>
        
        <div class="detail-actions">
          <el-button 
            type="primary" 
            @click="navigateToDetail(currentMessage)"
          >
            查看相关内容
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'
import { getUserMessages, markMessageAsRead } from '@/api/user'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 消息数据
const messages = ref<any[]>([])
const messageType = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalMessages = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const currentMessage = ref<any>(null)

// 计算属性：过滤后的消息
const filteredMessages = computed(() => {
  if (messageType.value === 'all') {
    return messages.value
  } else {
    return messages.value.filter(msg => msg.type === messageType.value)
  }
})

// 计算属性：是否有未读消息
const hasUnreadMessages = computed(() => {
  return messages.value.some(msg => !msg.isRead)
})

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    const userId = userInfoStore.userInfo?.user?.userId
    if (!userId) {
      ElMessage.warning('请先登录')
      return
    }
    
    const res = await getUserMessages(userId)
    console.log('获取消息响应:', res)
    
    // 处理响应数据
    if (res.data && res.data.code === 200) {
      // 标准响应格式
      if (Array.isArray(res.data.data)) {
        messages.value = res.data.data
      } else if (res.data.data && Array.isArray(res.data.data.records)) {
        messages.value = res.data.data.records
        totalMessages.value = res.data.data.total || res.data.data.records.length
      } else {
        console.warn('消息数据格式不是数组:', res.data.data)
        messages.value = []
      }
    } else if (Array.isArray(res.data)) {
      // 直接返回数组的情况
      messages.value = res.data
      totalMessages.value = res.data.length
    } else {
      console.error('获取消息失败:', res.data)
      ElMessage.error(res.data?.msg || '获取消息失败')
      messages.value = []
    }
  } catch (error) {
    console.error('获取消息错误:', error)
    ElMessage.error('网络错误，获取消息失败')
    messages.value = []
  } finally {
    loading.value = false
  }
}

// 标记消息为已读
const markAsRead = async (message: any) => {
  if (message.isRead) return
  
  try {
    const messageId = message.id
    if (!messageId) {
      console.error('消息ID不存在:', message)
      ElMessage.error('消息ID不存在，无法标记为已读')
      return
    }
    
    const res = await markMessageAsRead(messageId)
    console.log('标记消息已读响应:', res)
    
    // 更新本地消息状态
    message.isRead = true
    ElMessage.success('已标记为已读')
    
    // 更新全局未读消息数量
    // 这里可以触发一个事件或调用store中的方法更新全局未读消息数
  } catch (error) {
    console.error('标记消息已读错误:', error)
    ElMessage.error('标记已读失败')
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  if (!hasUnreadMessages.value) return
  
  try {
    ElMessageBox.confirm('确定要将所有消息标记为已读吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 实际项目中应该有一个批量标记API，这里简化为逐个标记
      const promises = messages.value
        .filter(msg => !msg.isRead)
        .map(msg => markMessageAsRead(msg.id))
      
      await Promise.all(promises)
      
      // 更新本地消息状态
      messages.value.forEach(msg => {
        msg.isRead = true
      })
      
      ElMessage.success('已全部标记为已读')
      
      // 更新全局未读消息数量
      // 这里可以触发一个事件或调用store中的方法更新全局未读消息数
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error) {
    console.error('标记全部已读错误:', error)
    ElMessage.error('操作失败')
  }
}

// 查看消息详情
const viewMessageDetail = (message: any) => {
  currentMessage.value = message
  dialogVisible.value = true
  
  // 如果是未读消息，标记为已读
  if (!message.isRead) {
    markAsRead(message)
  }
}

// 导航到相关内容
const navigateToDetail = (message: any) => {
  dialogVisible.value = false
  
  // 根据消息类型跳转到不同页面
  switch (message.type) {
    case 'review_reply':
      router.push(`/review?id=${message.relatedId}`)
      break
    case 'order_update':
      router.push(`/order?id=${message.relatedId}`)
      break
    case 'hotel_review':
      // 酒店商家查看评论
      router.push(`/my-hotel/reviews?id=${message.relatedId}`)
      break
    default:
      console.warn('未知消息类型:', message.type)
  }
}

// 过滤消息
const filterMessages = () => {
  currentPage.value = 1 // 重置页码
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 获取消息类型标签
const getTypeLabel = (type: string) => {
  switch (type) {
    case 'review_reply': return '评论回复'
    case 'order_update': return '订单更新'
    case 'hotel_review': return '酒店评价'
    default: return '系统通知'
  }
}

// 获取标签类型
const getTagType = (type: string) => {
  switch (type) {
    case 'review_reply': return 'success'
    case 'order_update': return 'primary'
    case 'hotel_review': return 'warning'
    default: return 'info'
  }
}

// 格式化时间
const formatTime = (time: string | number | Date) => {
  if (!time) return ''
  
  const date = new Date(time)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 今天
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } else if (diffDays === 1) {
    // 昨天
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } else {
    // 更早
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
}

// 组件挂载时获取消息数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.messages-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #8d6748;
  font-weight: bold;
}

.message-filter {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

/* 修改消息选择器的选中状态颜色为棕色 */
.message-filter :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: #8d6748;
  border-color: #8d6748;
  box-shadow: -1px 0 0 0 #8d6748;
  color: white;
}

/* 鼠标悬停时的颜色 */
.message-filter :deep(.el-radio-button__inner:hover) {
  color: #8d6748;
}

/* 聚焦时的颜色 */
.message-filter :deep(.el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled)) {
  box-shadow: 0 0 2px 2px rgba(141, 103, 72, 0.5);
}

/* 边框颜色 */
.message-filter :deep(.el-radio-button__inner) {
  border-color: #dcdfe6;
}

/* 选中相邻按钮的边框颜色 */
.message-filter :deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left-color: #dcdfe6;
}

.message-filter :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  border-left-color: #8d6748;
}

.message-list {
  margin-bottom: 20px;
}

.message-card {
  padding: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
  transition: all 0.3s;
  cursor: pointer;
}

.message-card:hover {
  box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.message-card.unread {
  border-left: 4px solid #67c23a;
  background-color: #f0f9eb;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.message-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.5;
}

.message-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 消息详情对话框样式 */
.message-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-time {
  font-size: 12px;
  color: #909399;
}

.detail-content {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 5px;
  margin-bottom: 20px;
  line-height: 1.6;
}

.detail-actions {
  display: flex;
  justify-content: center;
}
</style> 